<?php
/**
 * Класс корректирующий MVC-путь.
 *
 * @since 04.11.2011
 * @author Akulov Denis <akulov.d.g@gmail.com>
 */
class K_MVC_PathCorrector {

    private $arRules = array();


    private $arDefaultRoutes = array();


    public function __construct (K_Config $objConfig) {
        $this->arRules = $objConfig->getConfig('RULES_FOR_CORRECTION_REQUEST');
        $this->arDefaultRoutes = $objConfig->getConfig('DEFAULT_ROUTES');
    }


    public function requestCorrect ($request) {
        $request = strtolower($request);

        if (substr_count($request, '?') > 0) {
            $request = substr($request, 0, -strlen(strrchr($request, '?')));
        }

        if (substr($request, 0, 1) == '/') {
            $request = substr($request, 1);
        }

        if (substr($request, -1, 1) == '/') {
            $request = substr($request, 0, -1);
        }

        $firstPos = strlen(strchr($request, '/'));
        $partPath = '';
        if (empty($firstPos)) {
            $partPath = $request;
        } else {
            $partPath = substr($request, 0, -$firstPos);
        }

        foreach ($this->arRules as $pattern => $replacement){
            $partPath = preg_replace($pattern, $replacement, $partPath);
        }

        $request = $partPath.strchr($request, '/');

        $ajax = '';
        if (substr($request, 0, 5) == 'ajax/' || (strlen($request) == 4 && $request == 'ajax')) {
            $request = substr($request, 5);
            $ajax = 'ajax/';
        }

        if (empty($request)) {
            $request = $this->arDefaultRoutes['controller'].'/'.
                $this->arDefaultRoutes['method'];
        }

        if (substr_count($request, '/') == 0) {
            $request = $request.'/'.
                $this->arDefaultRoutes['method'];
        }

        return $ajax.$request;
    }

}